/* eslint-disable prefer-promise-reject-errors */
import axios from 'axios'
import { Notification } from 'element-ui'
import { $t } from './i18n'

const request = axios.create({
  // xsrfCookieName: getCsrfCookieName(),
  // xsrfHeaderName: 'X-CSRFToken',
  // withCredentials: true,
  // headers: {
  //   'X-Requested-With': 'XMLHttpRequest'
  // },
  // responseType: 'json',
  baseURL: process.env.VUE_APP_API_URL || '/',
  timeout: 12000
})

// request.interceptors.request.use(config => {

// })

request.interceptors.response.use(
  // if ((!response.data.result && String(response.data.code) === '401') || response.status === 401) {
  //   window.location.href = '/users/login/'
  //   Message.warning('未登录，跳转登录')
  //   throw Error('未登录')
  // }
  response => {
    const code = response.data.code
    // 登录之外，目前只有一种错误状态422请求参数传输错误
    if (code === 422) {
      Notification({ title: $t('数据参数错误'), type: 'error' })
      return Promise.reject($t('数据参数错误'))
    }
    return code === 200 ? response.data.data : Promise.reject(response.data.message)
  },
  error => {
    if (error.message === 'Network Error') {
      Notification({ title: $t('网络链接错误'), type: 'error' })
    } else if (error.message.startsWith('timeout')) {
      Notification({ title: $t('请求数据超时'), type: 'error' })
    }

    if (axios.isCancel(error)) return 'Cancel Request'

    return Promise.reject(error)
  }
)

export default request
